package com.lagou.utils;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.serialization.ClassResolver;
import io.netty.handler.codec.serialization.ObjectDecoder;

import java.util.List;

/**
 * 编码器实现：(现在传输的是RpcRequest, 需要编码器将请求对象转换为适合于传输的格式)
 */
public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;
    private Serializer serializer;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }


    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
       /* if (clazz != null && clazz.isInstance(msg)) {
            byte[] bytes = serializer.serialize(msg);
            byteBuf.writeInt(bytes.length);
            byteBuf.writeBytes(bytes);
        }*/
        ByteBuf byteBuf1 = in.skipBytes(4);
        byte[] data = new byte[byteBuf1.readableBytes()];
        ByteBuf byteBuf = byteBuf1.readBytes(data);
        RpcRequest deserialize = serializer.deserialize(RpcRequest.class,data);
        if (deserialize!=null){
            out.add(deserialize);
        }


    }
}
